package com.lvmama.rhino.web.comment.comment.controller;

import com.github.pagehelper.PageInfo;
import com.lvmama.rhino.pojo.comment.Enum.CommentDateRangeEnum;
import com.lvmama.rhino.pojo.comment.Enum.CommentDaysEnum;
import com.lvmama.rhino.pojo.comment.Enum.EnumForCategory;
import com.lvmama.rhino.pojo.comment.Enum.EnumForComment;
import com.lvmama.rhino.pojo.comment.entity.CommentDetail;
import com.lvmama.rhino.pojo.comment.entity.ViewDetail;
import com.lvmama.rhino.pojo.comment.query.CommentStatisticsQuery;
import com.lvmama.rhino.pojo.comment.request.CommentListRequest;
import com.lvmama.rhino.pojo.comment.request.ViewDetailRequest;
import com.lvmama.rhino.service.comment.CommentListService;
import com.lvmama.rhino.service.comment.CommentOverviewService;
import com.lvmama.rhino.service.impl.comment.RedisServiceImpl;
import com.lvmama.rhino.utils.Constants;
import com.lvmama.rhino.utils.DateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by hejing on 2017/9/5.
 */
@Controller
@RequestMapping("comment")
public class CommentListController {

    private Logger log = Logger.getLogger(CommentListController.class);
    @Autowired
    private CommentListService commentListService;
    @Autowired
    private CommentOverviewService commentOverviewService;

    @Autowired
    private RedisServiceImpl redisService;

    /**
     * 跳转到评论列表页面
     *
     * @param model
     * @param c1
     * @param flag
     * @return
     */
    @RequestMapping(value = "list")
    public String commentList(ModelMap model, CommentListRequest c1, String flag, String overviewDay) {
        try {
            // 品类
            EnumForCategory[] categories = EnumForCategory.getAllCategory();
            if (StringUtils.isNotBlank(c1.getSenseTypeName())) {
                int value = EnumForComment.getCommentValue(c1.getSenseTypeName());
                c1.setSenseType(String.valueOf(value));
            }
            if (StringUtils.isNotBlank(c1.getCategoryName())) {
                String categoryId = EnumForCategory.getCategoryValueByShowName(c1.getCategoryName());
                c1.setCategoryId(categoryId);
                model.put("categoryName", c1.getCategoryName());
            }
            model.put("categories", categories);
            // 评价
            EnumForComment[] comments = EnumForComment.getAllComment();
            model.put("comments", comments);
            model.put("flag", flag);
            model.put("page", new PageInfo<CommentDetail>());
            model.put("overviewDay", overviewDay);
            model.put("rangeName", c1.getRangeName());
            model.put("senseType", c1.getSenseType());
            model.put("productName", c1.getProductName());
            model.put("categoryId", c1.getCategoryId());
            model.put("chooseTime", c1.getChooseTime());
        } catch (Exception e) {
            e.printStackTrace();

        }
        return "application/commentAnalysis/commentList";
    }

    /**
     * 查询评论
     *
     * @param c1
     * @param flag
     * @return
     */
    @RequestMapping(value = "getCommentList")
    @ResponseBody
    public PageInfo<CommentDetail> commentList(CommentListRequest c1, String flag) {
        PageInfo<CommentDetail> commentDetailList = new PageInfo<>();
        try {
            log.info("comment getCommentList start");
            commentDetailList = getComments(c1);
            log.info("comment getCommentList end");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return commentDetailList;
    }

    // 观点提取
    @RequestMapping(value = "getViewPoint")
    @ResponseBody
    public List<ViewDetail> getViewPoint(ViewDetailRequest request) {
        List<ViewDetail> viewDetailList = new ArrayList<>();
        try {
            viewDetailList = commentListService.getViewPoint(request);
            // 枚举转换
            transViewEnum(viewDetailList);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return viewDetailList;
    }

    @RequestMapping(value = "deleteAllRedisKey")
    @ResponseBody
    public String deleteAllRedisKey() {
        try {
            log.info("comment deleteAllRedisKey start");
            redisService.deleteKeys(Constants.KEY_PREFIX);
            log.info("comment deleteAllRedisKey end");
            return "true";
        } catch (Exception e) {
            e.printStackTrace();
            log.error("comment deleteAllRedisKey error:" + e.getMessage(), e);
            return "" + e;
        }
    }

    private PageInfo<CommentDetail> getComments(CommentListRequest request) {
        PageInfo<CommentDetail> commentDetailList = new PageInfo<>();
        try {
            // 查询日期条件处理
            String overviewDay = request.getOverviewDay();
            String chooseTime = request.getChooseTime();
            if (CommentDaysEnum.YEAR.getCode().toString().equals(overviewDay) ||
                    CommentDaysEnum.HALF_A_MONTH.getCode().toString().equals(overviewDay)) {
                request.setChooseTime(null);
            } else if (StringUtils.isEmpty(chooseTime) && StringUtils.isEmpty(overviewDay)) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                request.setBeginDate(sdf.parse(DateUtil.getStrDate("7")));
                request.setEndDate(sdf.parse(DateUtil.getStrDate("1")));
            } else if (!StringUtils.isEmpty(chooseTime) && StringUtils.isEmpty(overviewDay)) {
                request.setOverviewDay(null);
                Map<String, Date> map = DateUtil.getSelectDate(request.getChooseTime());
                request.setBeginDate(map.get("beginDate"));
                request.setEndDate(map.get("endDate"));
            } else if (!StringUtils.isEmpty(chooseTime) && !StringUtils.isEmpty(overviewDay)) {
                request.setChooseTime(null);
            }

            if (StringUtils.isNotBlank(request.getRangeName())) {
                CommentDateRangeEnum rangeEnum = CommentDateRangeEnum.getEnumByName(request.getRangeName());
                if (null == rangeEnum) {
                    rangeEnum = CommentDateRangeEnum.WEEK;
                }
                request.setStartDateNum(rangeEnum.getStart());
                request.setEndDateNum(rangeEnum.getEnd());
            }
            commentDetailList = commentListService.getCommentList(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return commentDetailList;
    }

    /**
     * 观点提取枚举转换
     *
     * @param viewDetails
     */
    private void transViewEnum(List<ViewDetail> viewDetails) {
        if (!CollectionUtils.isEmpty(viewDetails)) {
            for (int i = 0; i < viewDetails.size(); i++) {
                ViewDetail viewDetail = viewDetails.get(i);
                // 情感极性
                int senseType = viewDetail.getSentiment();
                String senseTypeName = senseType > -1 ? EnumForComment.getCommentShowname(senseType) : "";
                viewDetail.setSentimentName(senseTypeName);
            }
        }
    }

    @RequestMapping("overview")
    public String overview(Model model, String mainFrame, HttpServletRequest request) {
        log.info("request overview start.");
        try {
            String days = request.getParameter("days");
            //查询出评论总数与指定天数评论数,默认7天
            CommentStatisticsQuery query = new CommentStatisticsQuery();
            query.setCancelGroupBy(true);
            if (StringUtils.isBlank(days)) {
                days = "7";
            }
            query.setDays(Integer.parseInt(days));
            Integer countByDays = commentOverviewService.selectAllCommentNum(query);
            //查询所有评论数
            query.setCancelLatestDay(true);
            query.setDays(0);
            Integer count = commentOverviewService.selectAllCommentNum(query);
            //切换查询天数（CommentDaysEnum）
            CommentDaysEnum daysEnum = CommentDaysEnum.getEnum(Integer.parseInt(days));
            if (null == daysEnum) {
                daysEnum = CommentDaysEnum.WEEK;
            }
            model.addAttribute("commentDaysName", daysEnum.getName());
            model.addAttribute("commentDaysCode", daysEnum.getCode());
            model.addAttribute("countByDays", countByDays);
            model.addAttribute("count", count);
        } catch (Exception e) {
            log.error("request overview error:" + e.getMessage(), e);
        }
        log.info("request overview end.");
        return "application/commentAnalysis/overview";
    }

}
